#!/usr/bin/env python
# coding=utf-8
"""
# @Created on : 2016/04/22 14:45
# @Author     : ldf (ldf@eehello.com)
# @Link       : http://www.eehello.com
# @Version    : 
# 本程序在python2.7下测试通过
"""

import SocketServer
import os

class myserver(SocketServer.BaseRequestHandler):

    def  handle(self):
        base_path = 'h:/temp'
        conn = self.request
        print 'connected...'
        while 1:
            pre_data = conn.recv(1024)
            #获取请求方法、文件名、文件大小
            cmd,file_name,file_size = pre_data.split('|')
            #已经接收文件的大小
            recv_size = 0
            #上传文件路径拼接
            file_dir = os.path.join(base_path,file_name)
            print file_dir
            f = open(file_dir, 'wb')
            flag = 1
            while flag:
                #未上传完毕
                if int(file_size) > recv_size:
                    #最多接受1024，可能接收的小于1024
                    data = conn.recv(1024)
                    recv_size += len(data)
                #上传完毕
                else:
                    recv_size = 0
                    flag = 0
                    continue
                #写入文件
                f.write(data)

            print('upload successed')
            f.close()

instance = SocketServer.ThreadingTCPServer(('127.0.0.1', 9999), myserver)
instance.serve_forever()
